<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <a-form :form="form" slot="detail">
        <a-row>
          <a-col :span="12">
            <a-form-item label="服务名称" :labelCol="labelCol" :wrapperCol="wrapperCol" style="margin-bottom: 15px">
              <a-input
                v-decorator="['projectName', validatorRules.projectName]"
                :maxLength="15"
                placeholder="请输入服务名称"
              ></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="所属果园" :labelCol="labelCol" :wrapperCol="wrapperCol" style="margin-bottom: 15px">
              <!-- <j-dict-select-tag type="list" v-decorator="['orchardId', validatorRules.orchardId]" :trigger-change="true" dictCode="txpp_orchard,name,id" placeholder="请选择所属果园"/> -->
              <j-multi-select-tag
                type="list_multi"
                v-decorator="['orchardId', validatorRules.orchardId]"
                :trigger-change="true"
                dictCode="txpp_orchard,name,id"
                placeholder="请选择所属果园"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="服务类型" :labelCol="labelCol" :wrapperCol="wrapperCol" style="margin-bottom: 15px">
              <j-dict-select-tag
                type="list"
                v-decorator="['projectType', validatorRules.projectType]"
                :trigger-change="true"
                dictCode="txpp_project_type"
                placeholder="请选择服务类型"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="推荐关键词" :labelCol="labelCol" :wrapperCol="wrapperCol" style="margin-bottom: 15px">
              <div v-decorator="['recommendedKeywords', validatorRules.recommendedKeywords]" style="margin-top: 10px">
                <template v-for="(tag, index) in recommendedKeywords">
                  <a-tooltip v-if="tag.length > 20" :key="tag" :title="tag">
                    <a-tag :key="tag" closable @close="() => handleClose(tag)">
                      {{ `${tag.slice(0, 20)}...` }}
                    </a-tag>
                  </a-tooltip>
                  <a-tag v-else :key="tag" closable @close="() => handleClose(tag)">
                    {{ tag }}
                  </a-tag>
                </template>
                <a-input
                  v-if="inputVisible"
                  ref="input"
                  type="text"
                  size="small"
                  :style="{ width: '78px' }"
                  :value="inputValue"
                  @change="handleInputChange"
                  @blur="handleInputConfirm"
                  @keyup.enter="handleInputConfirm"
                />
                <a-tag
                  v-if="!inputVisible && recommendedKeywords.length <= 2"
                  style="background: #fff; borderstyle: dashed"
                  @click="showInput"
                >
                  <a-icon type="plus" /> 新增
                </a-tag>
              </div>
            </a-form-item>
          </a-col>
          <!-- <a-col :span="12">
            <a-form-item label="开放开始时间" :labelCol="labelCol" :wrapperCol="wrapperCol" style="margin-bottom:15px">
              <j-date placeholder="请选择开放开始时间" v-decorator="['openingStartTime']" :trigger-change="true" style="width: 100%"/>
            </a-form-item>
          </a-col> -->
          <!-- <a-col :span="12">
            <a-form-item label="开放结束时间" :labelCol="labelCol" :wrapperCol="wrapperCol" style="margin-bottom:15px">
              <j-date placeholder="请选择开放结束时间" v-decorator="['openingEndTime']" :trigger-change="true" style="width: 100%"/>
            </a-form-item>
          </a-col> -->
          <a-col :span="12">
            <a-form-item label="推荐指数" :labelCol="labelCol" :wrapperCol="wrapperCol" style="margin-bottom: 15px">
              <a-rate
                v-decorator="['recommendationIndex', validatorRules.recommendationIndex]"
                placeholder="请选择推荐指数"
                style="margin-top: 10px"
              />
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <!-- <j-multi-select-tag type="list_multi" v-decorator="['variety']" :trigger-change="true" dictCode="dayOfWeek" placeholder="请选择果树品种"/> -->
            <a-form-item label="营业时间" :labelCol="labelCol" :wrapperCol="wrapperCol" style="margin-bottom: 15px">
              <div style="margin-bottom: 10px" v-for="(item, index) in businessHours" :key="index">
                <a-select
                  v-model="item.startDayOfWeek"
                  style="width: 90px"
                  @change="handleChange($event, index)"
                  placeholder="请选择"
                >
                  <a-select-option value="1"> 星期一 </a-select-option>
                  <a-select-option value="2"> 星期二 </a-select-option>
                  <a-select-option value="3"> 星期三 </a-select-option>
                  <a-select-option value="4"> 星期四 </a-select-option>
                  <a-select-option value="5"> 星期五 </a-select-option>
                  <a-select-option value="6"> 星期六 </a-select-option>
                  <a-select-option value="7"> 星期日 </a-select-option>
                </a-select>
                至
                <a-select
                  v-model="item.endDayOfWeek"
                  style="width: 90px"
                  @change="handleChange1($event, index)"
                  placeholder="请选择"
                >
                  <a-select-option value="1"> 星期一 </a-select-option>
                  <a-select-option value="2"> 星期二 </a-select-option>
                  <a-select-option value="3"> 星期三 </a-select-option>
                  <a-select-option value="4"> 星期四 </a-select-option>
                  <a-select-option value="5"> 星期五 </a-select-option>
                  <a-select-option value="6"> 星期六 </a-select-option>
                  <a-select-option value="7"> 星期日 </a-select-option>
                </a-select>
                <a-time-picker v-model="item.startTime" style="width: 115px; margin: 0 13px" format="HH:mm:ss" />
                <a-time-picker v-model="item.endTime" style="width: 115px" format="HH:mm:ss" />
                <a-icon
                  @click="del(businessHours, index)"
                  type="delete"
                  style="font-size: 18px; margin-left: 10px; color: rgb(217, 48, 38)"
                  v-if="businessHours.length > 1"
                />
              </div>
              <a-button
                v-if="businessHours.length <= 2"
                @click="addbusinessHours"
                icon="plus"
                style="width: 460px; margin: 10px 0"
              ></a-button>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="服务图片" :labelCol="labelCol" :wrapperCol="wrapperCol" style="margin-bottom: 20px">
              <j-image-upload
                isMultiple
                v-decorator="['projectPicture', validatorRules.projectPicture]"
              ></j-image-upload>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="服务简介" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-textarea
                maxLength="50"
                v-if="flag"
                :auto-size="{ minRows: 6, maxRows: 10 }"
                v-decorator="['projectIntroduction', { trigger: 'input' }]"
              ></a-textarea>
              <!-- <j-editor/> -->
            </a-form-item>
          </a-col>
          <a-col v-if="showFlowSubmitButton" :span="24" style="text-align: center">
            <a-button @click="submitForm">提 交</a-button>
          </a-col>
        </a-row>
      </a-form>
    </j-form-container>
  </a-spin>
</template>

<script>
import { httpAction, getAction } from '@/api/manage'
import pick from 'lodash.pick'
import { validateDuplicateValue } from '@/utils/util'
import JFormContainer from '@/components/jeecg/JFormContainer'
import JDate from '@/components/jeecg/JDate'
import JImageUpload from '@/components/jeecg/JImageUpload'
import JDictSelectTag from '@/components/dict/JDictSelectTag'
import JEditor from '@/components/jeecg/JEditor'
import moment from 'moment'
import JMultiSelectTag from '@/components/dict/JMultiSelectTag'
export default {
  name: 'TxppServiceItemsForm',
  components: {
    JFormContainer,
    JDate,
    JImageUpload,
    JDictSelectTag,
    JMultiSelectTag,
    JEditor,
  },
  props: {
    //流程表单data
    formData: {
      type: Object,
      default: () => {},
      required: false,
    },
    //表单模式：true流程表单 false普通表单
    formBpm: {
      type: Boolean,
      default: false,
      required: false,
    },
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false,
    },
  },
  data() {
    return {
      recommendedKeywords: [],
      inputVisible: false,
      inputValue: '',
      form: this.$form.createForm(this),
      businessHours: [
        {
          startDayOfWeek: undefined,
          endDayOfWeek: undefined,
          startTime: undefined,
          endTime: undefined,
        },
      ],
      flag: true,
      times: [
        {
          timeValue: '周一',
        },
        {
          timeValue: '周二',
        },
        {
          timeValue: '周三',
        },
        {
          timeValue: '周四',
        },
        {
          timeValue: '周五',
        },
        {
          timeValue: '周六',
        },
        {
          timeValue: '周日',
        },
      ],
      model: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      confirmLoading: false,
      validatorRules: {
        projectName: {
          rules: [{ required: true, message: '请输入服务名称!' }],
        },
        orchardId: {
          rules: [{ required: true, message: '请输入所属果园!' }],
        },
        recommendedKeywords: {
          rules: [{ required: true, message: '未填必填项!' }],
        },
        projectType: {
          rules: [{ required: true, message: '请输入服务类型!' }],
        },
        recommendationIndex: {
          rules: [{ required: true, message: '未填必填项!' }],
        },
        businessHoursList: {
          rules: [
            { required: true, message: '未填必填项!', trigger: 'blur' },
            // { validator: this.businessHoursValidate,trigger: 'blur'  }
          ],
        },
        projectPicture: {
          rules: [
            { required: true, message: '请上传服务图片!', trigger: 'blur' },
            // { validator: this.businessHoursValidate,trigger: 'blur'  }
          ],
        },
      },
      url: {
        add: '/loquat/txppServiceItems/add',
        edit: '/loquat/txppServiceItems/edit',
        queryById: '/dome/txppServiceItems/queryById',
      },
    }
  },
  computed: {
    formDisabled() {
      if (this.formBpm === true) {
        if (this.formData.disabled === false) {
          return false
        }
        return true
      }
      return this.disabled
    },
    showFlowSubmitButton() {
      if (this.formBpm === true) {
        if (this.formData.disabled === false) {
          return true
        }
      }
      return false
    },
  },
  created() {
    //如果是流程中表单，则需要加载流程表单data
    this.showFlowData()
  },
  mounted() {
    this.flag = false
    setTimeout(() => {
      this.flag = true
    }, 500)
  },
  methods: {
    businessHoursValidate(rule, value, callback) {
      console.log(this.businessHours)
      this.businessHours.map((item) => {
        if (item.startTime && item.endTime && item.startDayOfWeek && item.endDayOfWeek) {
          callback()
        } else {
          callback('营业时间不完整')
        }
      })
    },
    handleClose(removedTag) {
      const recommendedKeywords = this.recommendedKeywords.filter((tag) => tag !== removedTag)
      console.log(recommendedKeywords)
      this.recommendedKeywords = recommendedKeywords
    },
    showInput() {
      this.inputVisible = true
      this.$nextTick(function () {
        this.$refs.input.focus()
      })
    },

    handleInputChange(e) {
      this.inputValue = e.target.value
    },

    handleInputConfirm() {
      const inputValue = this.inputValue
      let recommendedKeywords = this.recommendedKeywords
      if (inputValue && recommendedKeywords.indexOf(inputValue) === -1) {
        recommendedKeywords = [...recommendedKeywords, inputValue]
      }
      this.recommendedKeywords = recommendedKeywords
      Object.assign(this, {
        recommendedKeywords,
        inputVisible: false,
        inputValue: '',
      })
    },
    addbusinessHours() {
      if (this.businessHours.length <= 2) {
        this.businessHours.push({
          startDayOfWeek: undefined,
          endDayOfWeek: undefined,
          startTime: undefined,
          endTime: undefined,
        })
      }
    },
    handleChange(e, index) {
      this.businessHours[index].startDayOfWeek = e
    },
    handleChange1(e, index) {
      this.businessHours[index].endDayOfWeek = e
    },
    del(items, index) {
      items.splice(index, 1)
    },
    add() {
      this.edit({})
      this.businessHours = [
        {
          startDayOfWeek: undefined,
          endDayOfWeek: undefined,
          startTime: undefined,
          endTime: undefined,
        },
      ]
    },
    edit(record) {
      this.form.resetFields()
      this.model = Object.assign({}, record)
      if (record.businessHoursList && record.businessHoursList.length > 0) {
        let rows = []
        record.businessHoursList.forEach((item, index) => {
          rows.push({
            startTime: record.businessHoursList[index].startTime
              ? moment(record.businessHoursList[index].startTime, 'HH:mm:ss')
              : undefined,
            endTime: record.businessHoursList[index].endTime
              ? moment(record.businessHoursList[index].endTime, 'HH:mm:ss')
              : undefined,
            startDayOfWeek: record.businessHoursList[index].startDayOfWeek
              ? record.businessHoursList[index].startDayOfWeek
              : undefined,
            endDayOfWeek: record.businessHoursList[index].endDayOfWeek
              ? record.businessHoursList[index].endDayOfWeek
              : undefined,
          })
        })
        this.businessHours = rows
      }
      this.recommendedKeywords = record.recommendedKeywords.split(',')
      this.visible = true
      this.$nextTick(() => {
        this.form.setFieldsValue(
          pick(
            this.model,
            'projectName',
            'orchardId',
            'projectType',
            'recommendedKeywords',
            'recommendationIndex',
            'businessHours',
            'projectPicture',
            'projectIntroduction'
          )
        )
      })
    },
    //渲染流程表单数据
    showFlowData() {
      if (this.formBpm === true) {
        let params = { id: this.formData.dataId }
        getAction(this.url.queryById, params).then((res) => {
          if (res.success) {
            this.edit(res.result)
          }
        })
      }
    },
    submitForm() {
      const that = this
      // 触发表单验证
      this.form.validateFields((err, values) => {
        const arr = []
        this.businessHours.map((item) => {
          if (!item.endDayOfWeek || !item.endTime || !item.startDayOfWeek || !item.startTime) {
            arr.push(item)
          }
        })
        if (arr.length) {
          this.$message.warning('请填写营业时间')
        } else {
          if (!err) {
            that.confirmLoading = true
            let httpurl = ''
            let method = ''
            if (!this.model.id) {
              httpurl += this.url.add
              method = 'post'
            } else {
              httpurl += this.url.edit
              method = 'put'
            }
            let formData = Object.assign(this.model, values)
            let businessHoursArr = []
            this.businessHours.forEach((i) => {
              businessHoursArr.push({
                startTime: i.startTime ? moment(i.startTime).format('HH:mm:ss') : '',
                endTime: i.endTime ? moment(i.endTime).format('HH:mm:ss') : '',
                startDayOfWeek: i.startDayOfWeek ? i.startDayOfWeek : '',
                endDayOfWeek: i.endDayOfWeek ? i.endDayOfWeek : '',
              })
            })
            formData.businessHoursList = businessHoursArr
            formData.recommendedKeywords = this.recommendedKeywords.join(',')
            console.log('表单提交数据', formData)
            httpAction(httpurl, formData, method)
              .then((res) => {
                if (res.success) {
                  that.$message.success(res.message)
                  that.$emit('ok')
                } else {
                  that.$message.warning(res.message)
                }
              })
              .finally(() => {
                that.confirmLoading = false
              })
          } else {
            let formData = Object.assign(this.model, values)
            console.log(formData, this.model, values)
          }
        }
      })
    },
    popupCallback(row) {
      this.form.setFieldsValue(
        pick(
          row,
          'projectName',
          'orchardId',
          'projectType',
          'recommendedKeywords',
          'recommendationIndex',
          'businessHours',
          'projectPicture',
          'projectIntroduction'
        )
      )
    },
  },
}
</script>
<style lang="less">
.ant-form-item-control {
  line-height: 0px !important;
}
.ant-col-sm-5 {
  width: 100px;
}
.projectstyle {
  .ant-col-sm-16 {
    width: 88%;
    .ant-form-item-control {
      .ant-form-item-children {
        > div {
          width: 95% !important;
        }
      }
    }
  }
}
</style>